package com.sls.game.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.PropertiesUtil;
import com.sls.core.util.ServerDateAndTime;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.common.DeductionRefund;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.DownstreamUserDAO;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.dao.SevenNineNineSixAssistDAO;
import com.sls.game.dao.SevenNineNineSixDAO;
import com.sls.game.page.Pagination;
import com.sls.game.parser.sls.OrderStatusSendParse;
import com.sls.game.parser.snns.ParseResponseInfo;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.DownstreamUserInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.pojo.snns.SevenNineNineSixProduct;
import com.sls.game.pojo.snns.SevenNineNineSixRechargeAssistInfo;
import com.sls.game.pojo.snns.SevenNineNineSixReqInfo;
import com.sls.game.pojo.snns.SevenNineNineSixRespInfo;
import com.sls.game.pojo.snns.SnnsAuxiliaryInfo;
import com.sls.game.pojo.snns.SnnsGoodsInfo;
import com.sls.game.service.SevenNineNineSixService;

@Service("snnsService")
public class SevenNineNineSixServiceImpl implements SevenNineNineSixService {

	private static Logger log = Logger
			.getLogger(SevenNineNineSixServiceImpl.class);
	private static String filename = "snns.properties";
	private Gson gson = null;
	@Resource(name = "goodsOrderDAO")
	private GoodsOrderDAO goodsOrderDAO;
	@Resource(name = "downstreamUserDAO")
	private DownstreamUserDAO downstreamUserDAO;

	@Resource(name = "sevenNineNineSixDAO")
	private SevenNineNineSixDAO sevenNineNineSixDAO;

	@Resource(name = "sevenNineNineSixAssistDAO")
	private SevenNineNineSixAssistDAO sevenNineNineSixAssistDAO;

	public SevenNineNineSixServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public SevenNineNineSixRespInfo queryOrder(String body, Head head) {
		SevenNineNineSixReqInfo reqInfo = gson.fromJson(body,
				SevenNineNineSixReqInfo.class);
		this.validate(reqInfo);
		if (StringUtils.isEmpty(reqInfo.getOid())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERNO_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERNO_NULL.getDescription());
		}
		HttpClient httpClient = new HttpClient();
		String url = this.assembleParameterForOrderQuery(reqInfo.getOid());
		SevenNineNineSixRespInfo resInfo = null;
		try {
			log.info("请求ID：" + head.getRequestId() + "--发送到7996订单查询请求参数：" + url);
			String xml = httpClient.doGet(url, "GB2312");
			log.info("请求ID：" + head.getRequestId() + "--7996订单查询返回给手拉手的请求结果："
					+ xml);
			if (StringUtils.isNotEmpty(xml)) {
				resInfo = ParseResponseInfo.parse(xml);
			}
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "--7996订单查询请求异常！", e);
			throw new ServerDisponseException(
					ExceptionCodeDes.HTTP_URL_FAILED.getCode(),
					ExceptionCodeDes.HTTP_URL_FAILED.getDescription());
		}
		return resInfo;
	}

	@Override
	public SevenNineNineSixRespInfo queryBalance(Head head) {
		HttpClient httpClient = new HttpClient();
		String url = this.assembleParameterForBalanceQuery();
		SevenNineNineSixRespInfo resInfo = null;
		try {
			log.info("请求ID：" + head.getRequestId() + "--发送到7996余额查询请求参数：" + url);
			String xml = httpClient.doGet(url, "GB2312");
			log.info("请求ID：" + head.getRequestId() + "--7996余额查询返回给手拉手的请求结果："
					+ xml);
			if (StringUtils.isNotEmpty(xml)) {
				resInfo = ParseResponseInfo.parse(xml);
			}
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "--7996余额查询请求异常！", e);
			throw new ServerDisponseException(
					ExceptionCodeDes.HTTP_URL_FAILED.getCode(),
					ExceptionCodeDes.HTTP_URL_FAILED.getDescription());
		}
		return resInfo;
	}

	@Override
	public void updateOrderStatus(String body, Head head) {
		SevenNineNineSixReqInfo asyncInfo = gson.fromJson(body,
				SevenNineNineSixReqInfo.class);
		// 成功处理时间
		String orderSuccessTime = ServerDateAndTime.getNowDateTime();
		String orderSuccessTime2 = ServerDateAndTime.getNowDateTimeOfFormat();
		boolean flag = this.checkData(asyncInfo);
		if (flag) {
			// 主动通知下游用户
			String userhandleResult = sendNotifyToDownUserMsg(asyncInfo,
					orderSuccessTime, head);
			updateGoodsOrder(head, asyncInfo, orderSuccessTime2,
					userhandleResult);
		}

	}

	private void updateGoodsOrder(Head head, SevenNineNineSixReqInfo asyncInfo,
			String orderSuccessTime, String userhandleResult) {

		// sls订单编号
		String orderNo = asyncInfo.getOid();
		// SUP平台订单号
		String supOrderNo = asyncInfo.getSid();
		// 订单交易状态
		String statusCode = asyncInfo.getSte();

		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		goodsOrderInfo.setOrderId(orderNo);
		goodsOrderInfo.setSupOrderId(supOrderNo);

		String status = "1";
		if ("0".equals(statusCode)) { // 成功
			status = "1";
		} else if ("1".equals(statusCode)) { // 失败
			status = "0";
			// 退款操作
			DeductionRefundInfo dedInfo = null;
			dedInfo = DeductionRefund.refundWhenAsynCallBackFailed(orderNo,
					goodsOrderDAO, head);
			String paymentStatus = "";
			if (dedInfo != null) {
				paymentStatus = dedInfo.getPaymentStatus();
			}
			if ("1".equals(paymentStatus)) { // 成功
				goodsOrderInfo.setIsPay("3"); // 退款成功
				// 退款成功，通知下游用户
				DeductionRefund.noticeUserRefundMsg(orderNo, dedInfo,
						goodsOrderDAO, downstreamUserDAO, null);

			} else if ("2".equals(paymentStatus)) {
				GoodsOrderInfo orderInfo = goodsOrderDAO
						.queryByOrderId(orderNo);
				if (orderInfo != null) {
					String isPayValue = orderInfo.getIsPay(); // 支付状态值
					if ("1".equals(isPayValue)) {
						goodsOrderInfo.setIsPay("2"); // 退款失败
					}
				}
			}
		}
		goodsOrderInfo.setStatus(status);
		goodsOrderInfo.setSupOrderSuccessTime(orderSuccessTime);
		goodsOrderInfo.setUserhandleResult(userhandleResult);
		goodsOrderInfo.setSynOrAsy("1"); // 异步推送
		// 数据更新
		try {
			goodsOrderDAO.update(goodsOrderInfo);
		} catch (Exception e) {
			log.error("7996异步推送更新订单异常", e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

	}

	private String sendNotifyToDownUserMsg(SevenNineNineSixReqInfo asyncInfo,
			String orderSuccessTime, Head head) {
		String handleResult = "FAILED";
		String orderId = asyncInfo.getOid();
		GoodsOrderInfo orderInfo = this.goodsOrderDAO.queryByOrderId(orderId);
		String notifyUrl = "";
		// 下游用户编号
		String contractId = null;
		if (orderInfo != null) {
			notifyUrl = orderInfo.getNotifyUrl();
			contractId = orderInfo.getContractId();

			String secretKey = null; // 下游用户密钥
			DownstreamUserInfo downstreamUserInfo = downstreamUserDAO
					.queryUserByUserNO(contractId);
			if (downstreamUserInfo != null) {
				secretKey = downstreamUserInfo.getSecretKey();
			}
			String httpUrl = notifyUrl
					+ "?"
					+ this.assembleParameter(asyncInfo, orderInfo, secretKey,
							orderSuccessTime);

			HttpClient httpClient = new HttpClient();
			// 供应商返回消息编码方式
			String supplyEncode = "UTF-8";
			// 给下游发消息
			String xmlStr = "";
			try {
				log.info("请求ID：" + head.getRequestId() + "，异步回调给下游用户的url："
						+ httpUrl);
				xmlStr = httpClient.doGet(httpUrl, supplyEncode);
				log.info("请求ID：" + head.getRequestId() + "，下游用户的返回结果：" + xmlStr);
			} catch (Exception e) {
				log.error("请求ID：" + head.getRequestId() + "，主动通知下游用户出现异常！", e);
			}
			if (xmlStr != null && !("".equals(xmlStr))) {
				SLSHttpInterfaceInfo slsInfo = null;
				slsInfo = OrderStatusSendParse.readUserSendMsg(xmlStr);
				if (slsInfo != null) {
					handleResult = slsInfo.getHandleResult();
				}
			}
		}
		return handleResult;
	}

	private String assembleParameter(SevenNineNineSixReqInfo asyncInfo,
			GoodsOrderInfo orderInfo, String secretKey, String orderSuccessTime) {
		// 下游用户订单号
		String ptOrderNo = orderInfo.getMerchantOrderId();
		// 手拉手订单号
		String supOrderNo = asyncInfo.getOid();
		// 充值后状态
		String orderState = asyncInfo.getSte();
		String err_msg = "";

		String logCodmsg = null;
		if ("0".equals(orderState)) { // 成功
			logCodmsg = "成功";
		} else if ("1".equals(orderState)) { // 失败
			logCodmsg = "失败";
		}
		log.info("异步推送过来的订单处理结果：  \n本地订单号:" + supOrderNo + "充值后状态:"
				+ logCodmsg + "处理时间:" + orderSuccessTime);

		StringBuilder strBui = new StringBuilder();
		strBui.append("ptOrderNo=");
		strBui.append(ptOrderNo);
		strBui.append("&");
		strBui.append("supOrderNo=");
		strBui.append(supOrderNo);
		strBui.append("&");
		strBui.append("status=");
		String status = null;
		if ("0".equals(orderState)) { // 成功
			status = "ORDER_SUCCESS";
			err_msg = ""; // ----------成功了为空
		} else if ("1".equals(orderState)) { // 失败
			status = "ORDER_FAILED";
			err_msg = "208"; // ---------失败
		}
		strBui.append(status);
		strBui.append("&");

		if ("ORDER_SUCCESS".equals(status)) { // ---------订单成功，才传成功充值时间
			strBui.append("supOrderSuccessTime=");
			strBui.append(orderSuccessTime);
			strBui.append("&");
		} else { // ---------------------订单失败时，才传错误码
			strBui.append("failedReason=");
			String fr = "";
			if (StringUtils.isNotBlank(err_msg)) {
				try {
					fr = URLEncoder.encode(err_msg, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					log.error("编码异常", e);
				}
			}
			strBui.append(fr);
			strBui.append("&");
		}

		strBui.append("sign=");
		String sign = createSign(ptOrderNo, supOrderNo, status,
				orderSuccessTime, err_msg, secretKey);
		strBui.append(sign);

		log.info("异步发送给下游用户的订单处理结果    \n 合作方订单编号:" + ptOrderNo + "\n 本地订单编号:"
				+ supOrderNo + "\n 订单最终处理结果：" + status + "\n订单处理的时间:"
				+ orderSuccessTime + "\n失败原因：" + err_msg);

		String result = strBui.toString().trim();
		return result;

	}

	/**
	 * 签名字符串
	 * 
	 * @param ptOrderNo
	 * @param supOrderNo
	 * @param status
	 * @param supOrderSuccessTime
	 * @param err_msg
	 * @return
	 */
	private String createSign(String ptOrderNo, String supOrderNo,
			String status, String supOrderSuccessTime, String err_msg,
			String secretKey) {
		StringBuilder strBui = new StringBuilder();
		strBui.append(ptOrderNo);
		strBui.append(supOrderNo);
		strBui.append(status);
		if (supOrderSuccessTime != null && !("".equals(supOrderSuccessTime))) {
			strBui.append(supOrderSuccessTime);
		}
		if (err_msg != null && !("".equals(err_msg))) {
			strBui.append(err_msg);
		}
		strBui.append(secretKey);
		String data = strBui.toString().trim();
		String result = UtilMD5Encryption.createMD5Encryption(data);
		return result;
	}

	private boolean checkData(SevenNineNineSixReqInfo asyncInfo) {
		boolean flag = false;
		if (StringUtils.isEmpty(asyncInfo.getSid())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getCode(),
					ExceptionCodeDes.COOPERATION_PLATFORM_ORDERNO_NULL
							.getDescription());
		} else if (StringUtils.isEmpty(asyncInfo.getOid())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERNO_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERNO_NULL.getDescription());
		} else if (StringUtils.isEmpty(asyncInfo.getSte())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.EN_LINK_RESULTCODE_EMPTY.getCode(),
					ExceptionCodeDes.EN_LINK_RESULTCODE_EMPTY.getDescription());
		} else {
			flag = true;
		}
		return flag;
	}

	private String assembleParameterForOrderQuery(String orderId) {
		String url = "";
		String address = PropertiesUtil.getValue(
				"snns.interface.query.order.address", filename);
		String cid = PropertiesUtil.getValue("snns.interface.cid", filename);
		String md5key = PropertiesUtil.getValue("snns.md5.key", filename);
		String data = orderId + cid + md5key;
		String sign = UtilMD5Encryption.createMD5EncryptionOfGBK(data);
		StringBuilder sb = new StringBuilder();
		sb.append(address);
		sb.append("?");
		sb.append("cid=");
		sb.append(cid);
		sb.append("&");
		sb.append("oid=");
		sb.append(orderId);
		sb.append("&");
		sb.append("type=0");
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);
		url = sb.toString();
		return url;
	}

	private String assembleParameterForBalanceQuery() {
		String url = "";
		String address = PropertiesUtil.getValue(
				"snns.interface.query.balance.address", filename);
		String cid = PropertiesUtil.getValue("snns.interface.cid", filename);
		String md5key = PropertiesUtil.getValue("snns.md5.key", filename);
		String data = cid + md5key;
		String sign = UtilMD5Encryption.createMD5EncryptionOfGBK(data);
		StringBuilder sb = new StringBuilder();
		sb.append(address);
		sb.append("?");
		sb.append("cid=");
		sb.append(cid);
		sb.append("&");
		sb.append("type=1");
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);
		url = sb.toString();
		return url;
	}

	private void validate(SevenNineNineSixReqInfo req) {
		if (req == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
	}

	/**
	 * 7996商品分页查询
	 * 
	 * @param body
	 * @param head
	 * @return
	 * @throws ServerDisponseException
	 */
	@Override
	public String queryPageInquire(String body, Head head)
			throws ServerDisponseException {
		// 对消息body进行解析
		SnnsGoodsInfo info = gson.fromJson(body, SnnsGoodsInfo.class);
		boolean flag = checkDataOfByPage(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixProduct query = new SevenNineNineSixProduct();
			query.setId(info.getId());
			query.setProductId(info.getProduct_id());
			query.setProductName(info.getProduct_name());
			query.setProductParvalue(info.getProduct_parvalue());
			query.setProductPrice(info.getProduct_price());
			query.setInsertTime(info.getInsert_time());
			query.setModifyTime(info.getModify_time());
			query.setIsAudit(info.getIsAudit());
			Pagination<SevenNineNineSixProduct> paginationList = null;
			paginationList = sevenNineNineSixDAO.queryProdutPage(query);
			String resultBody = null;
			if (paginationList != null) {
				List<SevenNineNineSixProduct> list = paginationList.getList();
				List<SnnsGoodsInfo> snnsList = new ArrayList<SnnsGoodsInfo>();
				for (SevenNineNineSixProduct product : list) {
					SnnsGoodsInfo snnsGoodsInfo = new SnnsGoodsInfo();
					snnsGoodsInfo.setId(product.getId());
					snnsGoodsInfo.setProduct_id(product.getProductId());
					snnsGoodsInfo.setProduct_name(product.getProductName());
					snnsGoodsInfo.setProduct_parvalue(product
							.getProductParvalue());
					snnsGoodsInfo.setProduct_price(product.getProductPrice());
					snnsGoodsInfo.setInsert_time(product.getInsertTime());
					snnsGoodsInfo.setModify_time(product.getModifyTime());
					snnsGoodsInfo.setIsAudit(product.getIsAudit());
					snnsList.add(snnsGoodsInfo);
				}
				Pagination<SnnsGoodsInfo> paginationListOfSnns = new Pagination<SnnsGoodsInfo>();
				paginationListOfSnns.setList(snnsList);
				paginationListOfSnns.setPageSize(paginationList.getPageSize());
				paginationListOfSnns.setCurrentPage(paginationList
						.getCurrentPage());
				paginationListOfSnns
						.setPageCount(paginationList.getPageCount());
				paginationListOfSnns.setRowCount(paginationList.getRowCount());
				resultBody = gson.toJson(paginationListOfSnns);
			}
			return resultBody;
		}

		return null;
	}

	/**
	 * 数据校验
	 */
	private boolean checkDataOfByPage(SnnsGoodsInfo info, String reqId)
			throws ServerDisponseException {
		boolean flag = false;
		String currentPage = info.getCurrentPage() + "";
		String pageSize = info.getPageSize() + "";
		if ("".equals(currentPage) || currentPage == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.CURRENT_PAGE_NULL.getCode(),
					ExceptionCodeDes.CURRENT_PAGE_NULL.getDescription());
		} else if ("".equals(pageSize) || pageSize == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PAGE_SIZE_NULL.getCode(),
					ExceptionCodeDes.PAGE_SIZE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 商品记录新增
	 * 
	 * @param body
	 * @param head
	 * @throws Exception
	 * 
	 */
	@Override
	public void save(String body, Head head) throws Exception {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		// 对消息body进行解析
		SnnsGoodsInfo info = gson.fromJson(body, SnnsGoodsInfo.class);
		boolean flag = checkDataOfSave(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixProduct product = sevenNineNineSixDAO
					.queryByProductId(info.getProduct_id());
			SevenNineNineSixProduct productInfo = new SevenNineNineSixProduct();
			if (product == null) { // 插入操作
				productInfo.setId(UUID.randomUUID().toString());
				productInfo.setProductId(info.getProduct_id());
				productInfo.setProductName(info.getProduct_name());
				productInfo.setProductParvalue(info.getProduct_parvalue());
				productInfo.setProductPrice(info.getProduct_price());
				String time = ServerDateAndTime.getNowDateTimeOfFormat();
				productInfo.setInsertTime(time);
				productInfo.setIsAudit("0"); // 未审核
				try {
					sevenNineNineSixDAO.insertProduct(productInfo);
				} catch (Exception e) {
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			} else { // 更新操作
				String id = product.getId();
				productInfo.setId(id);
				productInfo.setProductPrice(info.getProduct_price());
				String time = ServerDateAndTime.getNowDateTimeOfFormat();
				productInfo.setModifyTime(time);
				productInfo.setIsAudit("0"); // 未审核
				try {
					sevenNineNineSixDAO.updateProduct(productInfo);
				} catch (Exception e) {
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			}
		}
	}

	/**
	 * 记录插入数据校验
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfSave(SnnsGoodsInfo info, String reqId) {
		boolean flag = false;
		String product_id = info.getProduct_id();
		String product_name = info.getProduct_name();
		String product_parvalue = info.getProduct_parvalue();
		String product_price = info.getProduct_price();
		if ("".equals(product_id) || product_id == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PRODCODE_EMPTY.getCode(),
					ExceptionCodeDes.PRODCODE_EMPTY.getDescription());
		} else if ("".equals(product_name) || product_name == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.EN_LINK_PRODNAME_EMPTY.getCode(),
					ExceptionCodeDes.EN_LINK_PRODNAME_EMPTY.getDescription());
		} else if ("".equals(product_parvalue) || product_parvalue == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.GOODS_PARVALUE_NULL.getCode(),
					ExceptionCodeDes.GOODS_PARVALUE_NULL.getDescription());
		} else if ("".equals(product_price) || product_price == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.GOODS_IN_PRICE_NULL.getCode(),
					ExceptionCodeDes.GOODS_IN_PRICE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 商品辅助信息记录新增
	 * 
	 * @param body
	 * @param head
	 * @throws Exception
	 */
	@Override
	public void saveAuxiliary(String body, Head head) throws Exception {
		// 对消息body进行解析
		SnnsAuxiliaryInfo info = gson.fromJson(body, SnnsAuxiliaryInfo.class);
		boolean flag = checkDataOfAuxiliary(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixRechargeAssistInfo reAsInfo = new SevenNineNineSixRechargeAssistInfo();
			reAsInfo.setProductId(info.getProduct_id());
			reAsInfo.setArea(info.getArea());
			reAsInfo.setServer(info.getServer());
			SevenNineNineSixRechargeAssistInfo reAs = sevenNineNineSixAssistDAO
					.queryByCondition(reAsInfo);
			if (reAs == null) { // 插入操作
				reAsInfo.setId(UUID.randomUUID().toString());
				reAsInfo.setAccountType(info.getAccount_type());
				reAsInfo.setChargeType(info.getCharge_type());
				try {
					sevenNineNineSixAssistDAO.insertAssistInfo(reAsInfo);
				} catch (Exception e) {
					log.error(e);
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			} else { // 更新操作
				String id = reAs.getId();
				reAsInfo.setId(id);
				reAsInfo.setAccountType(info.getAccount_type());
				reAsInfo.setChargeType(info.getCharge_type());
				try {
					sevenNineNineSixAssistDAO.updateAssistInfo(reAsInfo);
				} catch (Exception e) {
					log.error(e);
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			}
		}
	}

	/**
	 * 辅助信息校验
	 * 
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfAuxiliary(SnnsAuxiliaryInfo info, String reqId) {
		boolean flag = false;
		String product_id = info.getProduct_id();
		if ("".equals(product_id) || product_id == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PRODCODE_EMPTY.getCode(),
					ExceptionCodeDes.PRODCODE_EMPTY.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 分页查询--辅助信息表
	 * @param body
	 * @param head
	 * @return
	 * @throws Exception
	 * @date 2013-04-27
	 */
	@Override
	public String queryAuxiByPage(String body, Head head) throws Exception {
		// 对消息body进行解析
		SnnsAuxiliaryInfo info = gson.fromJson(body, SnnsAuxiliaryInfo.class);
		boolean flag = checkDataOfAuxiByPage(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixRechargeAssistInfo query = new SevenNineNineSixRechargeAssistInfo();
			query.setId(info.getId());
			query.setProductId(info.getProduct_id());
			query.setArea(info.getArea());
			query.setServer(info.getServer());
			query.setAccountType(info.getAccount_type());
			query.setChargeType(info.getCharge_type());
			Pagination<SevenNineNineSixRechargeAssistInfo> paginationList = null;
			paginationList = sevenNineNineSixAssistDAO.queryAuxiByPage(query);
			String resultBody = null;
			if (paginationList != null) {
				List<SevenNineNineSixRechargeAssistInfo> list = paginationList.getList();
				List<SnnsAuxiliaryInfo> auxiList = new ArrayList<SnnsAuxiliaryInfo>();
				for (SevenNineNineSixRechargeAssistInfo reAsInfo : list){
					SnnsAuxiliaryInfo snnsAuxiInfo = new SnnsAuxiliaryInfo();
					snnsAuxiInfo.setId(reAsInfo.getId());
					snnsAuxiInfo.setProduct_id(reAsInfo.getProductId());
					snnsAuxiInfo.setArea(reAsInfo.getArea());
					snnsAuxiInfo.setServer(reAsInfo.getServer());
					snnsAuxiInfo.setAccount_type(reAsInfo.getAccountType());
					snnsAuxiInfo.setCharge_type(reAsInfo.getChargeType());
					auxiList.add(snnsAuxiInfo);
				}
				Pagination<SnnsAuxiliaryInfo> paginationListOfSnns = new Pagination<SnnsAuxiliaryInfo>();
				paginationListOfSnns.setList(auxiList);
				paginationListOfSnns.setPageSize(paginationList.getPageSize());
				paginationListOfSnns.setCurrentPage(paginationList
						.getCurrentPage());
				paginationListOfSnns
						.setPageCount(paginationList.getPageCount());
				paginationListOfSnns.setRowCount(paginationList.getRowCount());
				resultBody = gson.toJson(paginationListOfSnns);
			}
			log.info("分页查询结果为：  " + resultBody);
			if (log.isInfoEnabled()) {
				log.info("Service处理[" + head.getRequestId() + "]的请求已结束");
			}
			return resultBody;
		}
		
		return null;
	}
	
	/**
	 * 辅助信息表--分页查询  数据校验
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfAuxiByPage(SnnsAuxiliaryInfo info,String reqId){
		boolean flag = false;
		String currentPage = info.getCurrentPage() + "";
		String pageSize = info.getPageSize() + "";
		if ("".equals(currentPage) || currentPage == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.CURRENT_PAGE_NULL.getCode(),
					ExceptionCodeDes.CURRENT_PAGE_NULL.getDescription());
		} else if ("".equals(pageSize) || pageSize == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PAGE_SIZE_NULL.getCode(),
					ExceptionCodeDes.PAGE_SIZE_NULL.getDescription());
		} else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 根据商品Id，查询商品记录
	 * @param body
	 * @param head
	 * @return
	 * @throws Exception
	 * @date 2013-04-27
	 */
	@Override
	public String querySnnsGoodsById(String body, Head head) throws Exception {
		// 对消息body进行解析
		SnnsGoodsInfo info = gson.fromJson(body, SnnsGoodsInfo.class);
		boolean flag = checkDataOfGoodsById(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixProduct product = null;
			product = sevenNineNineSixDAO.queryByProductId(info.getProduct_id());
			if (product != null) {
				SnnsGoodsInfo snnsGoodsInfo = new SnnsGoodsInfo();
				snnsGoodsInfo.setId(product.getId());
				snnsGoodsInfo.setProduct_id(product.getProductId());
				snnsGoodsInfo.setProduct_name(product.getProductName());
				snnsGoodsInfo.setProduct_parvalue(product.getProductParvalue());
				snnsGoodsInfo.setProduct_price(product.getProductPrice());
				snnsGoodsInfo.setInsert_time(product.getInsertTime());
				snnsGoodsInfo.setModify_time(product.getModifyTime());
				snnsGoodsInfo.setIsAudit(product.getIsAudit());
				
				String resultBody = null;
				resultBody = gson.toJson(snnsGoodsInfo);
				return resultBody;
			}
		}
		
		return null;
	}
	
	/**
	 * 查询单条记录 --数据校验
	 * @param info
	 * @param reqId
	 */
	private boolean checkDataOfGoodsById(SnnsGoodsInfo info,String reqId){
		boolean flag = false;
		String product_id = info.getProduct_id();
		if ("".equals(product_id) || product_id == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.GOODS_ID_EMPTY.getCode(),
					ExceptionCodeDes.GOODS_ID_EMPTY.getDescription());
		}else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 商品记录更新
	 * @param body
	 * @param head
	 * @throws Exception
	 * @date 2013-04-27
	 */
	@Override
	public void updateOfSnnsGoodsInfo(String body, Head head) throws Exception {
		// 对消息body进行解析
		SnnsGoodsInfo info = gson.fromJson(body, SnnsGoodsInfo.class);
		boolean flag = checkDataOfUpdateGoods(info, head.getRequestId());
		if (flag) {
			SevenNineNineSixProduct product = new SevenNineNineSixProduct();
			product.setId(info.getId());
			product.setProductPrice(info.getProduct_price());
			product.setModifyTime(ServerDateAndTime.getNowDateTimeOfFormat());
			product.setIsAudit("0");
			try {
				sevenNineNineSixDAO.updateProduct(product);
			} catch (Exception e) {
				throw new ServerDisponseException(
						ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
						ExceptionCodeDes.ACCESS_DATABASE_ERROR
								.getDescription());
			}
		}
	}
		
	/**
	 * 记录更新数据校验
	 * @param info
	 * @param reqId
	 * @return
	 */
	private boolean checkDataOfUpdateGoods(SnnsGoodsInfo info,String reqId){
		boolean flag = false;
		String id = info.getId();
		String product_price = info.getProduct_price();
		if ("".equals(id) || id == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.ID_EMPTY.getCode(),
					ExceptionCodeDes.ID_EMPTY.getDescription());
		}else if ("".equals(product_price) || product_price == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.GOODS_IN_PRICE_NULL.getCode(),
					ExceptionCodeDes.GOODS_IN_PRICE_NULL.getDescription());
		}else {
			flag = true;
		}

		return flag;
	}

	/**
	 * 7996  配置文件读取
	 * @param body
	 * @param head
	 * @return
	 * @throws Exception
	 * @date 2013-04-27
	 */
	@Override
	public String readSnnsConfigFile(String body, Head head) throws Exception {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		String cid = PropertiesUtil.getValue("snns.interface.cid",
				"snns.properties").trim();
		SnnsGoodsInfo info = new SnnsGoodsInfo();
		info.setCid(cid);
		
		String resultBody = null;
		resultBody = gson.toJson(info);
		return resultBody;
	}	
	
	
}
